/**
 * 报表分类右键菜单
 * @param reportCategory 报表分类
 * @constructor
 */
var ReportCategoryMenu = function (reportCategory) {
    this.$reportZtreeMenu = $('#report_ztree_menu');
    this.reportCategory = reportCategory;
};

ReportCategoryMenu.prototype = {
    /**
     * 初始化 树形右键菜单
     */
    init: function () {
        var self = this;
        this.$reportZtreeMenu.menu({
            position: {my: "left top", at: "right-5 top+5"},
            classes: {
                "ui-menu": "highlight"
            },
            select: function (event, ui) {
                var index = $(event.currentTarget).index();
                var selectedNode = self.reportCategory.treeObj.getSelectedNodes()[0];
                if (undefined === selectedNode) {
                    $.xumf.gritterError('请选择分类！！！');
                    return;
                }
                switch (index) {
                    case 0:
                        self.reportCategory.addCategory(selectedNode);
                        break;
                    case 1:
                        self.reportCategory.modifyCategory(selectedNode);
                        break;
                    case 2:
                        self.reportCategory.removeCategory(selectedNode);
                        break;
                    default:
                }
                self.$reportZtreeMenu.hide();
            }
        }).mouseleave(function (e) {
            $(e.currentTarget).hide();
        });
    }
};

/**
 * 报表分类
 * @constructor
 */
var ReportCategory = function ($grid_selector) {
    this.treeId = 'report_tree';
    this.treeObj = null;
    this.$reportWidget = $('#report_widget');
    this.$grid_selector = $grid_selector;

    this.URL = {
        category: {
            add: '/report/category',
            edit: '/report/category/{{id}}',
            del: '/report/category/{{id}}'
        },
        ztree: {
            get: '/report/category/ztree/get'
        }
    };

    var self = this;
    // 树形配置
    this.treeSetting = {
        view: {
            dblClickExpand: false,
            selectedMulti: false
        },
        check: {enable: false},
        data: {simpleData: {enable: true}},
        async: {
            enable: true,//异步加载
            //请求地址，可用function动态获取
            url: this.URL.ztree.get,
            contentType: "application/x-www-form-urlencoded",//按照标准的 Form 格式提交参数
            autoParam: ["id"],//提交的节点参数，可用“id=xx”取请求提交时的别名
            dataType: "json",//返回数据类型
            type: "get",//请求方式
            dataFilter: null//数据过滤
        },
        callback: {
            onClick: function (event, treeId, treeNode) {
                self.OnLeftClick(event, treeId, treeNode)
            },
            onRightClick: function (event, treeId, treeNode) {
                self.OnRightClick(event, treeId, treeNode);
            }
        }
    };

    this.reportCategoryTemplate = _.template('\
    <div style="padding: 0 12px 0 12px;">\
        <form style="padding: 12px;" class="form-horizontal" method="post" id="category_form">\
            <input type="hidden" name="rcId" value="{{rcId}}">\
            <input type="hidden" name="parentId" value="{{parentId}}">\
            <div class="form-group">\
                <label for="parentId" class="col-xs-1 control-label">父分类</label>\
                <div class="col-xs-11">\
                    <input value="{{parentText}}" autocomplete="off" class="form-control" id="parentId" disabled/>\
                </div>\
            </div>\
            <div class="form-group">\
                <label for="name" class="col-xs-1 control-label">名称</label>\
                <div class="col-xs-11">\
                    <input value="{{name}}" autocomplete="off" class="form-control" name="name" id="name"/>\
                </div>\
            </div>\
            <div class="form-group">\
                <label for="status" class="col-xs-1 control-label">状态</label>\
                <div class="col-xs-5">\
                    <label class="radio-inline">\
                        <input {{on}} type="radio" name="status" id="status" value="1">开启\
                    </label>\
                    <label class="radio-inline">\
                        <input {{off}} type="radio" name="status" id="status" value="0">禁用\
                    </label>\
                </div>\
                <label for="sequence" class="col-xs-1 control-label">序号</label>\
                <div class="col-xs-5">\
                    <input value="{{sequence}}" autocomplete="off" min="1" type="number" class="form-control" id="sequence" name="sequence">\
                </div>\
            </div>\
            <div class="form-group">\
                <label for="comment" class="col-xs-1 control-label">备注</label>\
                <div class="col-xs-11">\
                    <input value="{{comment}}" autocomplete="off" class="form-control" id="comment" name="comment">\
                </div>\
            </div>\
            </form>\
        </div>\
    ');
};

/**
 * 报表分类
 * @type {{init: ReportCategory.init, initWidget: ReportCategory.initWidget, addCategory: ReportCategory.addCategory, modifyCategory: ReportCategory.modifyCategory, removeCategory: ReportCategory.selectedNode, addCategoryAction: function(*=): *, modifyCategoryAction: function(*=): *, validateAction: function(*, *=): *, resetTree: ReportCategory.resetTree, refreshSelectedNode: ReportCategory.refreshSelectedNode, refreshSelectedNodeParentNode: ReportCategory.refreshSelectedNodeParentNode, refreshNode: ReportCategory.refreshNode, beforeClick: ReportCategory.beforeClick, OnLeftClick: ReportCategory.OnLeftClick, OnRightClick: ReportCategory.OnRightClick}}
 */
ReportCategory.prototype = {
    init: function () {

        var $grid_selector = this.$grid_selector;
        this.initWidget();
        this.resetTree();
        // 初始化右键菜单功能
        var reportCategoryMenu = new ReportCategoryMenu(this);
        reportCategoryMenu.init();
        // 绑定右键事件
        this.OnRightClick = function (event, treeId, treeNode) {
            if (treeNode === null) return;
            $.fn.zTree.getZTreeObj(treeId).selectNode(treeNode);
            reportCategoryMenu.$reportZtreeMenu.css({
                top: event.pageY - 100,
                left: event.pageX - 200
            }).slideDown(100);
            // 重载报表数据
            $grid_selector.setGridParam({datatype: 'json', postData: {searchString: treeNode.id}})
                .trigger('reloadGrid');
        };
        // 绑定左键事件
        this.OnLeftClick = function (event, treeId, treeNode) {
            // 重载报表数据
            $grid_selector.setGridParam({datatype: 'json', postData: {searchString: treeNode.id}})
                .trigger('reloadGrid');
        };
    },
    /**
     * widget 中的添加与刷新分类树事件
     */
    initWidget: function () {

        var self = this;
        this.$reportWidget
            .on('setting.ace.widget', function (e) {
                self.addCategory({id: $.Const.ROOT_ID, name: $.Const.ROOT_TEXT});
                e.preventDefault();
            })
            .on('reload.ace.widget', function (e) {
                self.resetTree();
                e.preventDefault();
            });
    },
    /**
     * 添加报表分类
     * @param selectedNode 选择的节点
     */
    addCategory: function (selectedNode) {
        var self = this;
        var data = {
            rcId: '',
            parentId: selectedNode.id,
            parentText: selectedNode.name,
            sequence: '1',
            comment: '',
            name: '',
            on: 'checked',
            off: ''
        };
        layer.open({
            title: '新增分类',
            area: ['650px', '330px'],
            content: this.reportCategoryTemplate(data),
            yes: function (index, layero) {
                self.addCategoryAction(selectedNode.id === $.Const.ROOT_ID) && layer.close(index);
            }
        });
    },
    /**
     * 编辑报表分类
     * @param selectedNode 选择的节点
     */
    modifyCategory: function (selectedNode) {
        var self = this;
        var parentText;
        var parenId = selectedNode.pId;
        if (parenId === $.Const.ROOT_ID || null === parenId) {
            parentText = $.Const.ROOT_TEXT;
        } else {
            debugger
            parentText = selectedNode.getParentNode().name;
        }
        var data = {
            rcId: selectedNode.id,
            parentId: selectedNode.pId,
            parentText: parentText,
            sequence: selectedNode.sequence,
            comment: selectedNode.comment,
            name: selectedNode.name,
            on: selectedNode.status === 1 ? 'checked' : '',
            off: selectedNode.status === 0 ? 'checked' : ''
        };
        layer.open({
            title: '编辑数据源',
            area: ['650px', '330px'],
            content: this.reportCategoryTemplate(data),
            yes: function (index, layero) {
                self.modifyCategoryAction(selectedNode.pId === $.Const.ROOT_ID) && layer.close(index);
            }
        });
    },
    /**
     * 删除报表分类
     * @param selectedNode 选择的节点
     */
    removeCategory: function selectedNode(selectedNode) {
        var self = this;
        layer.confirm('<div style="padding:12px;">确定删去该分类？</div>', function (index, layero) {
            $.xumf.ajaxAndLoading({
                type: 'DELETE',
                url: _.template(self.URL.category.del)({id: selectedNode.pId}),
            }).success(function (res) {
                $.xumf.gritter(res);
                if (res.success) {
                    self.treeObj.removeNode(selectedNode);
                    layer.close(index);
                }
            });
        });
    },
    /**
     * 添加操作
     * @param isParentRoot 当前新增或者修改的父节点是否为根节点
     * @returns {boolean} 是否阻止dialog消失，true为消失，false则相反
     */
    addCategoryAction: function (isParentRoot) {
        var $form = $('#category_form');
        $form.attr('action', this.URL.category.add);
        return this.validateAction($form, isParentRoot, 'POST');
    },
    /**
     * 编辑操作
     * @param isParentRoot 当前新增或者修改的父节点是否为根节点
     * @returns {boolean} 是否阻止dialog消失，true为消失，false则相反
     */
    modifyCategoryAction: function (isParentRoot) {
        var $form = $('#category_form');
        var rcId = $form.find('input[name=rcId]').val();
        $form.attr('action', _.template(this.URL.category.edit)({id: rcId}));
        return this.validateAction($form, isParentRoot, 'PUT');
    },
    /**
     * 验证与提交
     * @param $form 表单的jquery对象
     * @param isParentRoot 当前新增或者修改的父节点是否为根节点
     * @param type from请求类型
     * @returns {*} 验证是否成功
     */
    validateAction: function ($form, isParentRoot, type) {
        var self = this;
        $form.validate({
            rules: {
                rcId: {required: true},
                name: {required: true},
                comment: {required: true},
                sequence: {required: true},
                parentId: {required: true},
                status: {required: true}
            },
            errorElement: "em"
        });
        // 验证成功
        var valid = $form.valid();
        if (valid) {
            $.xumf.showLoading();
            $form.ajaxSubmit({
                type: type,
                success: function (res) {
                    $.xumf.hideLoading();
                    $.xumf.gritter(res);
                    if (res.success) {
                        if (isParentRoot) {
                            self.refreshNode(null)
                        } else {
                            self.refreshSelectedNodeParentNode()
                        }
                    }
                }
            });
        }
        return valid;
    },
    /**
     * 重新加载分类树
     */
    resetTree: function () {
        var self = this;
        $.get(this.URL.ztree.get, {id: $.Const.ROOT_ID}).done(function (res) {
            $.fn.zTree.init($('#' + self.treeId), self.treeSetting, res.data);
            self.treeObj = $.fn.zTree.getZTreeObj(self.treeId);
        });
    },
    /**
     * 刷新当前选中节点
     */
    refreshSelectedNode: function () {
        var nodes = this.treeObj.getSelectedNodes();
        nodes.length > 0 && this.treeObj.reAsyncChildNodes(nodes[0], "refresh");

    },
    /**
     * 刷新当前选中节点的父节点
     */
    refreshSelectedNodeParentNode: function () {
        var nodes = this.treeObj.getSelectedNodes();
        nodes.length > 0 && this.refreshNode(nodes[0]);
    },
    /**
     * 通过节点id刷新节点
     *
     * @param node 节点
     */
    refreshNode: function (node) {
        if (node === null) {
            this.treeObj.reAsyncChildNodes(null, "refresh");
        } else {
            this.treeObj.reAsyncChildNodes(node.getParentNode(), "refresh");
        }
    },
    /**
     * 树形点击前事件
     * @param treeId 树形id
     * @param treeNode 节点对象
     */
    beforeClick: function (treeId, treeNode) {
        // 如果不是父节点
        if (!treeNode.isParent) {
        }
    },
    /**
     * 树形左键事件
     * @param event 事件对象
     * @param treeId 树形id
     * @param treeNode 节点对象
     * @constructor
     */
    OnLeftClick: function (event, treeId, treeNode) {
    },
    /**
     * 树形右键事件
     * @param event 事件对象
     * @param treeId 树形id
     * @param treeNode 节点对象
     * @constructor
     */
    OnRightClick: function (event, treeId, treeNode) {
    }
};